<template>
  <div class="layout">
    <div class="header">
      <div class="logo">
        <i class="el-icon-orange"></i>
        虾塘养殖管理系统
      </div>
      <div class="user-info">
        <el-dropdown>
          <span class="el-dropdown-link">
            <el-avatar
              :size="36"
              :src="currentUser?.avatar || ''"
              style="margin-right: 10px"
            ></el-avatar>
            {{ currentUser?.name || "用户"
            }}<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="goToProfile">个人信息</el-dropdown-item>
              <el-dropdown-item divided @click="logout"
                >退出登录</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <div class="main-container">
      <div class="sidebar">
        <div class="menu-title">主菜单</div>
        <el-menu
          :default-active="$route.path"
          class="el-menu-vertical-demo"
          background-color="#2a3f4e"
          text-color="#fff"
          active-text-color="#ffd04b"
          :unique-opened="true"
          router
        >
          <el-menu-item index="/dashboard">
            <i class="el-icon-data-line"></i>
            <span>控制台</span>
          </el-menu-item>

          <el-sub-menu index="2">
            <template #title>
              <i class="el-icon-user"></i>
              <span>用户管理</span>
            </template>
            <el-menu-item index="/users">用户列表</el-menu-item>
            <el-menu-item index="/profile" v-if="!isAdmin"
              >个人信息</el-menu-item
            >
          </el-sub-menu>

          <el-sub-menu index="3">
            <template #title>
              <i class="el-icon-help"></i>
              <span>虾塘管理</span>
            </template>
            <el-menu-item index="/ponds">我的虾塘</el-menu-item>
            <el-menu-item index="/all-ponds" v-if="isAdmin"
              >全部虾塘</el-menu-item
            >
            <el-menu-item index="/add-pond">添加虾塘</el-menu-item>
          </el-sub-menu>

          <el-sub-menu index="4">
            <template #title>
              <i class="el-icon-cpu"></i>
              <span>装置管理</span>
            </template>
            <el-menu-item index="/devices">装置列表</el-menu-item>
            <el-menu-item index="/add-device">添加装置</el-menu-item>
            <el-menu-item index="/command">下发命令</el-menu-item>
          </el-sub-menu>

          <el-sub-menu index="5">
            <template #title>
              <i class="el-icon-video-camera"></i>
              <span>视频监控</span>
            </template>
            <el-menu-item index="/upload-video" v-if="!isAdmin"
              >上传视频</el-menu-item
            >
            <el-menu-item index="/review-video" v-if="isAdmin"
              >视频审核</el-menu-item
            >
            <el-menu-item index="/videos">视频列表</el-menu-item>
          </el-sub-menu>

          <el-sub-menu index="6">
            <template #title>
              <i class="el-icon-bell"></i>
              <span>报警管理</span>
            </template>
            <el-menu-item index="/alerts">待处理报警</el-menu-item>
            <el-menu-item index="/alert-history">报警历史</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </div>

      <div class="content">
        <router-view></router-view>
      </div>
    </div>
  </div>
</template>

<script>
import { logout as apiLogout } from "@/api/login";
import { computed, onMounted, ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessageBox, ElMessage, ElLoading } from "element-plus";

export default {
  name: "CommonLayout",
  setup() {
    const store = useStore();
    const router = useRouter();
    const isLogoutLoading = ref(false);

    // 添加默认用户信息
    const defaultUser = ref({
      name: "用户",
      avatar: "",
      role: "user",
    });

    const isAdmin = computed(() => store.getters.isAdmin);
    const currentUser = computed(() => {
      const user = store.getters.currentUser;
      // 如果用户信息为null或undefined，返回默认值
      return user || defaultUser.value;
    });

    // 初始化用户信息
    onMounted(() => {
      // 检查store中的用户信息，如果不存在则设置默认值
      if (!store.getters.currentUser) {
        store.commit("setUser", defaultUser.value);
      }
    });

    const goToProfile = () => {
      router.push("/profile");
    };

    // 清除登录相关信息
    const clearLoginInfo = () => {
      // 清除localStorage中的信息
      localStorage.removeItem("accessToken");
      localStorage.removeItem("refreshToken");
      localStorage.removeItem("accessExpiresIn");
      localStorage.removeItem("refreshExpiresIn");
      localStorage.removeItem("accessExpiryTime");
      localStorage.removeItem("refreshExpiryTime");
      localStorage.removeItem("userInfo");
      localStorage.removeItem("openIdWeb");
      localStorage.removeItem("userId");

      // 清除Vuex中的用户信息
      store.commit("setUser", null);
      store.commit("setLoginStatus", false);
    };

    const logout = async () => {
      ElMessageBox.confirm("确定要退出登录吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          isLogoutLoading.value = true;
          const loadingInstance = ElLoading.service({
            lock: true,
            text: "退出中...",
            background: "rgba(0, 0, 0, 0.7)",
          });

          try {
            // 调用退出登录接口
            const logoutRes = await apiLogout();

            if (logoutRes.code === 0) {
              // 清除登录信息
              clearLoginInfo();
              // 跳转到登录页（使用replace避免返回）
              router.replace("/login");
              ElMessage.success(logoutRes.message || "退出登录成功");
            } else {
              throw new Error(logoutRes.message || "退出登录失败");
            }
          } catch (error) {
            console.error("退出登录失败:", error);
            // 即使接口失败也清除本地信息
            clearLoginInfo();
            router.replace("/login");
            ElMessage.error(error.message || "退出失败，请重试");
          } finally {
            isLogoutLoading.value = false;
            loadingInstance.close();
          }
        })
        .catch(() => {
          // 取消退出
        });
    };

    return {
      isAdmin,
      currentUser,
      goToProfile,
      logout,
      isLogoutLoading,
    };
  },
};
</script>

<style scoped>
.layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.header {
  background-color: #1b9a7c;
  color: white;
  padding: 0 20px;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  font-size: 22px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.logo i {
  margin-right: 10px;
  font-size: 24px;
}

.user-info {
  display: flex;
  align-items: center;
}

.main-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 220px;
  background-color: #2a3f4e;
  color: #fff;
  overflow-y: auto;
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.menu-title {
  padding: 15px 20px;
  font-size: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  color: #a6b3bf;
}

.el-menu {
  border-right: none;
}

.el-menu-item,
.el-sub-menu__title {
  color: #e0e0e0;
}

.el-menu-item:hover,
.el-sub-menu__title:hover {
  background-color: #1b9a7c !important;
  color: #fff;
}

.el-menu-item.is-active {
  background-color: #1b9a7c !important;
  color: #fff;
}
</style>
